<template>
	<view class="login-container">
		<uni-card>
			<view class="login-title">
				<text>电梯管理系统</text>
			</view>

			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-forms-item label="用户名" name="username">
					<uni-easyinput v-model="formData.username" placeholder="请输入用户名" />
				</uni-forms-item>

				<uni-forms-item label="密码" name="password">
					<uni-easyinput v-model="formData.password" type="password" placeholder="请输入密码" />
				</uni-forms-item>
			</uni-forms>

			<view class="btn-group">
				<button class="login-btn" @click="handleLogin" :loading="loading">
					登录
				</button>
				<view class="register-link" @click="goToRegister">
					还没有账号？立即注册
				</view>
			</view>
		</uni-card>
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request';

	export default {
		data() {
			return {
				loading: false,
				formData: {
					username: '',
					password: ''
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '请输入用户名'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请输入密码'
						}]
					}
				}
			};
		},

		methods: {
			async handleLogin() {
				try {
					const valid = await this.$refs.form.validate();
					if (!valid) return;

					this.loading = true;
					const res = await request({
						url: '/api/auth/login',
						method: 'POST',
						data: this.formData
					});

					if (!res || !res.token) {
						throw new Error('Invalid response from server');
					}

					// Save token and user info
					uni.setStorageSync('token', res.token);
					uni.setStorageSync('user', res.user);

					uni.showToast({
						title: '登录成功',
						icon: 'success'
					});

					// Navigate to home page
					uni.reLaunch({
						url: '/pages/index/index'
					});
				} catch (err) {
					console.error('Login error:', err);
					uni.showToast({
						title: err.message || '登录失败',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.loading = false;
				}
			},

			goToRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				});
			}
		}
	};
</script>

<style>
	.login-container {
		padding: 20px;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
	}

	.login-title {
		font-size: 24px;
		text-align: center;
		margin-bottom: 30px;
	}

	.btn-group {
		margin-top: 30px;
	}

	.login-btn {
		width: 100%;
		height: 40px;
		line-height: 40px;
		text-align: center;
		background-color: #007AFF;
		color: #fff;
		border-radius: 4px;
	}

	.register-link {
		margin-top: 15px;
		text-align: center;
		color: #007AFF;
		font-size: 14px;
	}
</style>